package br.com.util;

import java.io.File;
import java.util.HashMap;
import java.util.HashSet;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.mapper.MapperWrapper;

import br.com.ldml.Tripla;
import br.com.tmp.Temp;

public class TripleSet {
	HashMap<String, HashMap<String, HashSet<String>>> tripleSet;

	public TripleSet() {
		tripleSet = new HashMap<String, HashMap<String, HashSet<String>>>();
	}
	
	public TripleSet(String variableName) {
		XStream xs = new XStream() {
			protected MapperWrapper wrapMapper(MapperWrapper next) {  
				return new MapperWrapper(next) {  
					public boolean shouldSerializeMember(@SuppressWarnings("rawtypes") Class definedIn, String fieldName) {  
						return definedIn != Object.class ? super.shouldSerializeMember(definedIn, fieldName) : false;  
					}  
				};  
			}  
		};
		
		xs.processAnnotations(new Class[] { Tripla.class, Temp.class } );
		
		String baseXml = "C:/Augusto/Programas/workspace/emml/WebContent/WEB-INF/classes/" + variableName + ".xml";
		
		Temp t = (Temp) xs.fromXML(new File(baseXml));
		
		tripleSet = new HashMap<String, HashMap<String, HashSet<String>>>();
		for(Tripla tr : t.getTriplas()) {
			addTriple(tr);
		}
	}
	
	public void addTriple(Tripla tr) {
		if(tripleSet == null) return;
		
		if(tripleSet.containsKey(tr.getSujeito())) {
			if(tripleSet.get(tr.getSujeito()).containsKey(tr.getPredicado())) {
				tripleSet.get(tr.getSujeito()).get(tr.getPredicado()).add(tr.getObjeto());
			} else {
				HashSet<String> hs = new HashSet<String>();
				hs.add(tr.getObjeto());
				
				tripleSet.get(tr.getSujeito()).put(tr.getPredicado(), hs);
			}
		} else {
			HashSet<String> hs = new HashSet<String>();
			hs.add(tr.getObjeto());
			
			HashMap<String, HashSet<String>> hm = new HashMap<String, HashSet<String>>();
			hm.put(tr.getPredicado(), hs);
			
			tripleSet.put(tr.getSujeito(), hm);
		}
	}
	
	public boolean hasSubject(String subject) {
		return (tripleSet == null) ? false : tripleSet.containsKey(subject);
	}
	
	public boolean hasProperty(String property) {
		for(String subject : tripleSet.keySet()) {
			if(tripleSet.get(subject).containsKey(property)) {
				return true;
			}
		}
		return false;
	}
	
	public boolean hasObject(String object) {
		for(String subject : tripleSet.keySet()) {
			for(String property : tripleSet.get(subject).keySet()) {
				if(tripleSet.get(subject).get(property).contains(object)) {
					return true;
				}
			}
		}
		
		return false;
	}
	
	public HashMap<String, HashMap<String, HashSet<String>>> getTripleSet() {
		return tripleSet;
	}

	public void setTripleSet(HashMap<String, HashMap<String, HashSet<String>>> tripleSet) {
		this.tripleSet = tripleSet;
	}
}
